import fetch from 'node-fetch';
import {createLogger} from './Logger.js';

/**
 * 简单的 Elasticsearch HTTP 客户端
 */
export class ElasticsearchClient {
    constructor(baseUrl, verbose = false) {
        this.baseUrl = typeof baseUrl === 'string' ? baseUrl.replace(/\/$/, '') : '';
        this.verbose = verbose;
        this.logger = createLogger('Elasticsearch');
    }

    /**
     * 发送搜索请求
     * @param {{index: string, body: object}} payload
     * @returns {Promise<any>}
     */
    async search(payload) {
        if (!payload?.index || !payload?.body) {
            throw new Error('Elasticsearch 查询参数不完整，缺少 index 或 body');
        }
        if (!this.baseUrl) {
            throw new Error('Elasticsearch 基础地址未配置');
        }
        const url = `${this.baseUrl}/${payload.index}/_search`;
        if (this.verbose) {
            this.logger.debug(`请求地址: ${url}`);
            this.logger.debug(`请求体: ${JSON.stringify(payload.body)}`);
        }
        let response;
        try {
            response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload.body)
            });
        } catch (error) {
            throw new Error(`Elasticsearch 请求失败: ${error.message}`);
        }
        const text = await response.text();
        if (this.verbose) {
            this.logger.debug(`响应: status=${response.status} body=${text}`);
        }
        if (!response.ok) {
            throw new Error(`Elasticsearch 查询失败，HTTP 状态码 ${response.status}`);
        }
        try {
            return JSON.parse(text);
        } catch (error) {
            throw new Error(`Elasticsearch 查询结果解析失败: ${error.message}`);
        }
    }
}
